﻿package com.guavestudios.fcon.util {
	import flash.events.KeyboardEvent;
	import flash.ui.Keyboard;
	
	/**
	* ...
	* @author Default
	*/
	public class KeyMatcher {
		
		public static const LINE_REG:RegExp =/^(?:(?:(?:\+|)(?:(?<alt>alt)|(?<crtl>crtl)|(?<shift>shift))){0,3}\+|)(?:Key\.(?:(?<keycode>\d{1,3})|(?<keyname>[A-Z_]{2,15}))|Char\.(?<char>\d{2,3})|Char\.(?<charname>.))$/;

		public static function createMatcher(s:String):KeyMatcher
		{
			var cm:KeyMatcher = new KeyMatcher();
			
			if (s == null) return cm;
			if (s.length == 0) return cm;
			
			var res:Object = LINE_REG.exec(s);
			if (res != null)
			{
				if (res[1] != undefined) cm.alt = true;
				if (res[2] != undefined) cm.crtl = true;
				if (res[3] != undefined) cm.shift = true;
				if (res[4] != undefined) cm.code = parseInt(res[4]);
				if (res[5] != undefined) cm.code = Keyboard[res[5]];
				if (res[6] != undefined) cm.char = parseInt(res[6]);
				if (res[7] != undefined) cm.char = String(res[7]).charCodeAt(0);
			}
			else
			{
				throw new Error("WRONG SYNTAX: "+s);
			}
			return cm;
		}
		
		private var _code:int = -1;
		private var _char:int = -1;
		private var _shift:Boolean = false;
		private var _crtl:Boolean = false;
		private var _alt:Boolean = false;
		
		public function KeyMatcher() {
			
		}
		
		public function matchEvent(e:KeyboardEvent):Boolean
		{
			var match:Boolean = false;
			if (_code > -1 && e.keyCode==_code)
			{
				match = true;
				match = match && (alt == e.shiftKey);
			}
			else if (_char > -1 && e.charCode==_char)
			{
				match = true;
			}
			
			match = match && (_alt == e.altKey);
			match = match && (_crtl == e.ctrlKey);
			
			return match;
		}
		
		public function get code():int { return _code; }
		
		public function set code(value:int):void {
			_code = value;
		}
		
		public function get char():int { return _char; }
		
		public function set char(value:int):void {
			_char = value;
		}
		
		public function get shift():Boolean { return _shift; }
		
		public function set shift(value:Boolean):void {
			_shift = value;
		}
		
		public function get crtl():Boolean { return _crtl; }
		
		public function set crtl(value:Boolean):void {
			_crtl = value;
		}
		
		public function get alt():Boolean { return _alt; }
		
		public function set alt(value:Boolean):void {
			_alt = value;
		}
		
		public function toString():String
		{
			return "KeyMatcher(crtl: " + _crtl + ", alt: " + _alt + ", shift: " + _shift + ", key: " + _code + ", char: " + _char + ")";
		}
		
	}
	
}